package com.jgp.config;

import com.jgp.sys.repository.JGPRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019/3/26
 */
@Order(100)
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@EntityScan(basePackages = "com.**.model", basePackageClasses = Jsr310JpaConverters.class)
@EnableJpaRepositories(basePackages = "com.**.repository", repositoryFactoryBeanClass = JGPRepositoryFactoryBean.class)
public class PersistConfiguration {
    
    public PersistConfiguration() {
    }
    
    //实体管理工厂builder
    @Autowired
    private EntityManagerFactoryBuilder factoryBuilder;
    
    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;
    
    @Autowired
    private JpaProperties jpaProperties;
    
    
    @Resource
    private HibernateProperties hibernateProperties;
    
    /**
     * 配置第二个实体管理工厂的bean
     * @return
     */
    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return factoryBuilder.dataSource(dataSource)
                             .properties(properties)
                             .packages("com.**.model")
                             .persistenceUnit("persistenceUnit")
                             .build();
    }
    
    /**
     * jpa事务管理
     * @return
     */
    @Primary
    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return jpaTransactionManager;
    }

}
